var $;
var layer;
var table;
var form;

    layui.use(['layer', 'table', 'form'], function () {
        layer = layui.layer;
        $ = layui.jquery;
        table = layui.table;
        form = layui.form;

        getClass();
        getiInitialize();

        //初始化用户信息——表格
        function getiInitialize(){
            $.post("/login/selUserContent", {}, function (res) {
                if (res.code>-1) {
                    $("#UserId").val(res.obj.userId);
                    var uId=$("#UserId").val();
                    getTab(uId,"","","",null);
                } else {
                    layer.msg("数据加载失败", {icon: 2});
                }
            });
        }

        //查询课程分类
        function getClass(){
            $.ajax({
                url: "/tea/selCourseClass",
                type: "get",
                dataType: "json",
                success: function (data) {
                    //初始化树
                    ztree(data.obj);
                },
                error: function () {
                    layer.msg("数据获取失败！");
                }
            });
        }



        //初始化ztree
        function ztree(data) {
            var setting = {
                data: {
                    simpleData: {
                        enable:true, //true 、 false 分别表示 使用 、 不使用 简单数据模式
                        idKey:"id", //节点数据中保存唯一标识的属性名称
                        pIdKey:"parentId",   //节点数据中保存其父节点唯一标识的属性名称
                        rootPId: -1 //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                    },
                    key: {
                        name:"menuName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                    }
                },
                check:{
                    enable:false, //true 、 false 分别表示 显示 、不显示 复选框或单选框
                    nocheckInherit:true  //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
                },
                callback:{
                    onClick:ztreeOnClick,
                    beforeClick : validStatus
                },view: {
                    dblClickExpand: false,
                    showIcon: false
                }
            };

            zTreeObj = $.fn.zTree.init($("#ztreeId"), setting, data);//初始化树
            zTreeObj.expandAll(true);   //true 节点全部展开、false节点收缩
        };

        //禁止父节点点击
        function validStatus(treeId, treeNode, clickFlag) {
            if (treeNode.children.length>0) {
                layer.msg('不能选择父分类');
                return false;
            }
            return true;
        }

        //点击节点获取值
        function ztreeOnClick(event,treeId,treeNode){
            var uId=$("#UserId").val();
            getTab(uId,"","","",treeNode.nodeid);
            $("#classId").val(treeNode.nodeid);
            return false;
        };

        //获取课程的数据
        function getTab(uId,title,phone,account,classId,likenum,collectnum,hitsnum,sharenum,date,date2){
            $.ajax({
                url:"/tea/selForumTab",
                type:"post",
                dataType:"json",
                contentType:"application/json",
                data:JSON.stringify({"uId":uId,"title":title,"phone":phone,"account":account, "classId":classId,
                    "articleLike":likenum,"collectNum":collectnum,"articleHits":hitsnum,"articleShare":sharenum
                    ,"createDate":date,"createDate2":date2}),
                success:function(data){
                    tab(data.obj);
                },
                error: function () {
                    layer.msg('数据获取失败！');
                }
            });
        }

        //表格渲染
        function tab(data) {
            table.render({
                elem: '#forumTab',
                data:data
                ,toolbar: '#toolbarDemo'//开启头部工具栏，并为其绑定左侧模板
                ,defaultToolbar: []//自定义头部工具栏右侧图标
                ,title: '个人微圈数据表'
                ,page:true
                ,limit:5
                ,cols: [[
                    {type: 'checkbox', fixed: 'left'}
                    ,{field:'microcircleId', title:'ID',hide:true}
                    ,{title:'排序',width:67,fixed:'left',templet(da){//templet 通过这个函数可以实现逻辑处理，比如时间戳的转换
                            return da.LAY_INDEX;/*返回它的序列号*/}}
                    ,{field:'userName', title:'用户昵称',width:86}
                    ,{field:'articleTitle', title:'文章名称',width:160}
                    ,{field:'createDate', title:'创建时间',width:170,templet(da){
                            var createDate=settime(da.createDate);
                            return "<div>"+createDate+"</div>"
                        }}
                    ,{field:'userAccount', title:'用户账号',width:108}
                    ,{field:'articleLike', title:'点赞数'}
                    ,{field:'collectNum', title:'收藏数'}
                    ,{field:'articleHits', title:'查看量'}
                    ,{field:'articleShare', title:'分享量'}
                    ,{title:'操作', width:90,templet(da){
                        return "<p><a onclick='javascript:getMicroCircle("+da.microcircleId+")'>查看</a>" +
                                "<a onclick='javascript:delMicroCircle("+da.microcircleId+")'>删除</a></p>";
                     }}
                ]]
            });
        }

        /*日期转换*/
        function settime(da){
            var date=new Date(da);
            var year=date.getFullYear();
            var month=date.getMonth()+1;
            var day=date.getDate();
            var hours=date.getHours();
            var mm=date.getMinutes();
            var s=date.getSeconds();
            return year+'-'+add(month)+'-'+add(day)+' '+add(hours)+':'+add(mm)+':'+add(s);
            //return year+'-'+month+'-'+day+' '+hours+':'+mm+':'+s;
        };
        function add(time){//给非整数添0
            return time<10?'0'+time:time;
        };

        //查询按钮
        $("#queryButId").on("click",function(){
            var title=$("#title").val();
            var phone=$("#phone").val();
            var account=$("#account").val();
            var uId=$("#UserId").val();
            getTab(uId,title,phone,account,null);
        });

        //高级检索
        $("#retrievalButId").on("click",function(){
            layer.open({
                type:2,
                title:"高级检索",
                area:['550px','400px'],
                shade:0.4,
                offset:'auto',
                content:"MCRretrieval.html"
            });
            window.layer_3=layer;//将当前弹出层的对象赋值给window对象
        });
        //检索出的表格
        setTab =function () {
            var uphone=$("#uphone").val();
            var date=$("#createDate").val();//开始时间
            var date2=$("#createDate2").val();//结束时间
            var likenum=$("#articleLike").val();
            var collectnum=$("#collectNum").val();
            var hitsnum=$("#articleHits").val();
            var sharenum=$("#articleShare").val();
            var uId=$("#UserId").val();
            getTab(uId,"",uphone,"",null,likenum,collectnum,hitsnum,sharenum,date,date2);
        };
    });
//查看-编辑微圈
function getMicroCircle(id) {
    layer.open({
        type:2,
        title:"微圈管理",
        area:['1200px','600px'],
        shade:0.4,
        offset:['10px','100px'],
        maxmin: true,
        content:"TeaManageMC.html",
        success:function(layero,index) {
            //查找当前引入的iframe内容
            var obj = layero.find('iframe').contents();
            //根据选择器选择input,并设置值
            obj.find('input[name=mcId]').val(id);
        }
    });
    window.layer_4=layer;
};

//删除课程
function delMicroCircle(id) {
    layer.open({
        type: 1,
        title: "删除文章",
        area: ['200px', '200px'],
        shade: 0.4,
        offset: 'auto',
        content:"<p id='layerpId'>确定删除该文章吗？</p>",
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            $.post("/tea/delMicroCircle", {id: id}, function (res) {
                if (res.code>-1) {
                    layer.msg("删除成功", {icon: 1},function(){
                        layer.close(index);
                        location.reload();//刷新页面
                    });
                } else {
                    layer.msg("数据加载失败", {icon: 2});
                }
            });
        },
        btn2: function (index, layero) {
            layer.close(index);
        }
    })
}

//添加微圈文章
function addMC() {
    var classId=$("#classId").val();
    layer.open({
        type:2,
        title:"添加文章",
        area:['800px','600px'],
        shade:0.4,
        offset:'auto',
        maxmin: true,
        content:"TeaAddMC.html?classId="+classId,
        success:function(layero,index) {
            var obj = layero.find('iframe').contents();
            var uId=$("#UserId").val();
            obj.find('input[name=userId]').val(uId);
        },
        end:function () {
            location.reload();
        }
    });
    //将当前弹出层的对象赋值给window对象
    window.layer_3=layer;
};

//刷新按钮
$("#breakbtn").on("click",function () {
    location.reload();//刷新页面
});
//返回按钮
$("#returnbtn").on("click",function () {
    history.go(-1);//数据全部还在 //history.back(-1)//直接返回当前页的上一页，是个新页面
});

//重置按钮
$("#resetButId").on("click",function () {
    $("#title").val("");
    $("#phone").val("");
    $("#account").val("");
    var uId=$("#UserId").val();
    getTab(uId,"","","",null);
});